// initial state
import { StoreOptions } from "vuex";
import ACCESS_ENUM from "@/access/accessEnum";
import { UserControllerService } from "../../generated";

// 添加请求缓存和防重复请求机制
let getUserPromise: Promise<any> | null = null;

export default {
  namespaced: true,
  state: () => ({
    loginUser: {
      userName: "未登录",
      userRole: ACCESS_ENUM.NOT_LOGIN,
    },
    isLoading: false,
  }),
  actions: {
    async getLoginUser({ commit, state }, payload) {
      // 如果正在请求中，返回现有的Promise
      if (getUserPromise) {
        console.log("正在获取用户信息，复用现有请求...");
        return getUserPromise;
      }

      // 如果传入了payload，直接更新状态
      if (payload) {
        commit("updateUser", payload);
        return;
      }

      commit("setLoading", true);

      try {
        // 创建新的请求Promise
        getUserPromise = UserControllerService.getLoginUserUsingGet();

        // 请求后端，获取当前的登录信息
        const res = await getUserPromise;
        console.log("获取用户信息响应:", res);

        if (res.code === 0) {
          commit("updateUser", {
            ...res.data,
            userRole: res.data.userRole || ACCESS_ENUM.USER, // 确保有默认角色
          });
        } else {
          console.log("用户未登录或登录已过期");
          commit("updateUser", {
            userName: "未登录",
            userRole: ACCESS_ENUM.NOT_LOGIN,
          });
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        // 网络错误时保持当前状态，避免强制登出
        if (!state.loginUser.userRole) {
          commit("updateUser", {
            userName: "未登录",
            userRole: ACCESS_ENUM.NOT_LOGIN,
          });
        }
        throw error; // 重新抛出错误，让调用方知道请求失败
      } finally {
        commit("setLoading", false);
        getUserPromise = null; // 清除Promise缓存
      }
    },

    // 登出操作
    logout({ commit }) {
      commit("updateUser", {
        userName: "未登录",
        userRole: ACCESS_ENUM.NOT_LOGIN,
      });
    },
  },
  mutations: {
    updateUser(state, payload) {
      console.log("更新用户状态:", payload);
      state.loginUser = payload;
    },

    setLoading(state, isLoading) {
      state.isLoading = isLoading;
    },
  },
} as StoreOptions<any>;
